import { fetchEventSource } from '@microsoft/fetch-event-source';

export const useFetchStream = async (
  url: string,
  args: any,
  {
    onMessage,
    onEnd,
    onError,
    onClose,
    headers = {},
    method = 'post',
  }: {
    onMessage?: (data: any) => void;
    onEnd?: () => void;
    onError?: (err: any) => void;
    onClose?: () => void;
    headers?: Record<string, string>;
    method?: string;
  } = {},
) => {
  fetchEventSource(url, {
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    method,
    body: JSON.stringify({ ...args }),
    openWhenHidden: true,
    onmessage: e => {
      if (!e.data) return;
      const data = JSON.parse(e.data);
      onMessage && onMessage(data);
      if (data.event === 'message_end') {
        onEnd && onEnd();
      }
    },
    onerror: err => {
      onError ? onError(err) : console.error(err);
    },
    onclose: () => {
      onClose && onClose();
    },
  });
};
